import React, { useEffect, useState } from 'react';
import { Card, Table, Button, DialogPlugin, MessagePlugin, Input, Select, Tag, Switch } from 'tdesign-react';
import { AddIcon, EditIcon, DeleteIcon, RefreshIcon } from 'tdesign-icons-react';

import { JupiterUser, JupiterUserRole } from '../../types/userTypes';
import { JupiterRole } from '../../types/roleTypes';
import { formatTime } from '../../utils/timeutil';

import {
  fetchUserList,
  createUser,
  updateUser,
  deleteUser,
  restoreUser,
  fetchUserRoles,
  updateUserStatus,
  resetUserPassword,
  assignRolesToUser,
} from '../../services/userService';
import {
  getAllActiveRolesService,
} from '../../services/roleService';

import UserForm from './components/UserForm';
import UserRoleForm from './components/UserRoleForm';

const { Option } = Select;

export default function UsersPage() {
  const [userList, setUserList] = useState<JupiterUser[]>([]);
  const [loading, setLoading] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [formUserRoleVisible, setFormUserRoleVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<Partial<JupiterUser>>();
  const [title, setTitle] = useState('新增用户');
  const [searchUsername, setSearchUsername] = useState('');
  const [searchNickname, setSearchNickname] = useState('');
  const [searchStatus, setSearchStatus] = useState<number | undefined>();
  const [allActiveRoles, setAllActiveRoles] = useState<JupiterRole[]>();
  const [selectedRoles, setSelectedRoles] = useState<string[]>();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const getList = async () => {
    setLoading(true);
    try {
      const params = {
        username: searchUsername,
        nickname: searchNickname,
        isActive: searchStatus,
        page: pagination.current,
        size: pagination.pageSize,
      };
      const res = await fetchUserList(params);
      if (res.data) {
        setUserList(res.data.records || []);
        setPagination(prev => ({
          ...prev,
          total: res.data.total || 0,
        }));
      }
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingUser(undefined);
    setTitle('新增用户');
    setFormVisible(true);
  };

  const handleEdit = (record: JupiterUser) => {
    setEditingUser(record);
    setTitle('编辑用户');
    setFormVisible(true);
  };


  const getAllActiveRoles = async () => {
    try {
      const res = await getAllActiveRolesService();
      setAllActiveRoles(res.data);
    } catch (error) {
      MessagePlugin.error('获取角色列表失败');
    }
  };

  const getAllUserRoles = async (uuid: string) => {
    try {
      const res = await fetchUserRoles(uuid);
      setSelectedRoles(res.data);
    } catch (error) {
      MessagePlugin.error('获取角色列表失败');
    }
  };

  const handleEditUserRole = (record: JupiterUser) => {
    setEditingUser(record);
    getAllUserRoles(record.uuid)
    getAllActiveRoles()
    setFormUserRoleVisible(true);
  };

  const handleEditUserRoleSubmit = async (data: Partial<JupiterUserRole>) => {
    await assignRolesToUser(data);
    MessagePlugin.success('更新成功');
    setFormUserRoleVisible(false);
  };
  const handleDelete = (record: JupiterUser) => {
    const confirmDialog = DialogPlugin.confirm({
      header: '删除确认',
      body: `确定删除用户【${record.username}】？`,
      closeOnOverlayClick: false,
      onConfirm: async () => {
        await deleteUser(record.uuid);
        MessagePlugin.success('删除成功');
        getList();
        confirmDialog.hide();
      },
      onCancel: () => {
        confirmDialog.hide();
      },
      onClose: () => {
        confirmDialog.hide();
      },
    });
  };

  const handleRestore = (record: JupiterUser) => {
    const confirmDialog = DialogPlugin.confirm({
      header: '删除确认',
      body: `确定恢复用户【${record.username}】？`,
      closeOnOverlayClick: false,
      onConfirm: async () => {
        await restoreUser(record.uuid);
        MessagePlugin.success('恢复成功');
        getList();
        confirmDialog.hide();
      },
      onCancel: () => {
        confirmDialog.hide();
      },
      onClose: () => {
        confirmDialog.hide();
      },
    });
  };

  const handleSubmit = async (data: Partial<JupiterUser>) => {
    if (editingUser?.uuid) {
      await updateUser(editingUser.uuid, data);
      MessagePlugin.success('更新成功');
    } else {
      await createUser(data);
      MessagePlugin.success('创建成功');
    }
    setFormVisible(false);
    getList();
  };

  const handleStatusChange = async (record: JupiterUser, status: number) => {
    try {
      await updateUserStatus(record.uuid, status);
      MessagePlugin.success('状态更新成功');
      getList();
    } catch (error) {
      MessagePlugin.error('状态更新失败');
    }
  };

  const handleResetPassword = async (record: JupiterUser) => {
    const confirmDialog = DialogPlugin.confirm({
      header: '重置密码确认',
      body: `确定重置用户【${record.username}】的密码？`,
      closeOnOverlayClick: false,
      onConfirm: async () => {
        await resetUserPassword(record.uuid);
        MessagePlugin.success('密码重置成功');
        confirmDialog.hide();
      },
      onCancel: () => {
        confirmDialog.hide(); // 取消时手动关闭
      },
      onClose: () => {
        confirmDialog.hide(); // 右上角叉号关闭
      },
    });
  };

  useEffect(() => {
    getList();
  }, [pagination.current, pagination.pageSize, searchUsername, searchNickname, searchStatus]);

  return (
    <Card title="用户管理">
      <div style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', gap: 16, marginBottom: 16 }}>
          <Input
            placeholder="搜索用户名"
            value={searchUsername}
            onChange={(value) => setSearchUsername(value)}
            onEnter={() => getList()}
            style={{ width: 150 }}
          />
          <Input
            placeholder="搜索昵称"
            value={searchNickname}
            onChange={(value) => setSearchNickname(value)}
            onEnter={() => getList()}
            style={{ width: 150 }}
          />
          <Select
            placeholder="选择状态"
            value={searchStatus}
            onChange={(value) => setSearchStatus(value as number)}
            clearable
            style={{ width: 120 }}
          >
            <Option value={1} label="启用">
              启用
            </Option>
            <Option value={0} label="禁用">
              禁用
            </Option>
          </Select>
          <Button theme="primary" onClick={getList}>
            查询
          </Button>
          <Button theme="primary" onClick={handleCreate}>
            新增用户
          </Button>
        </div>
      </div>

      <Table
        data={userList}
        rowKey="uuid"
        loading={loading}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showJumper: true,
          onChange: (pageInfo) => {
            setPagination(prev => ({
              ...prev,
              current: pageInfo.current,
              pageSize: pageInfo.pageSize,
            }));
          },
        }}
        columns={[
          {
            colKey: 'username',
            title: '用户名',
            width: 120,
          },
          {
            colKey: 'nickname',
            title: '昵称',
            width: 120,
          },
          {
            colKey: 'email',
            title: '邮箱',
            width: 200,
          },
          {
            colKey: 'phone',
            title: '手机号',
            width: 130,
          },
          {
            colKey: 'status',
            title: '状态',
            width: 100,
            cell: ({ row }) => (
              <Tag theme={row.isActive === true ? 'success' : 'warning'}>
                {row.isActive === true ? '启用' : '禁用'}
              </Tag>
            ),
          },
          {
            colKey: 'lastLoginTime',
            title: '最后登录时间',
            width: 180,
            cell: ({ row }) => formatTime(row.lastLoginTime || ""),
          },
          {
            colKey: 'createTime',
            title: '创建时间',
            width: 180,
            cell: ({ row }) => formatTime(row.createTime || ""),
          },
          {
            colKey: 'delete_status',
            title: '删除状态',
            width: 100,
            cell: ({ row }) => (
              <Tag theme={row.deleteTime ? 'danger' : 'success'}>
                {row.deleteTime ? '已删除' : '正常'}
              </Tag>
            ),
          },
          {
            colKey: 'operation',
            title: '操作',
            width: 250,
            cell: ({ row }) => (
              <>
                {row.deleteTime === null ? (
                  <>
                    <Button
                      theme="primary"
                      variant="text"
                      icon={<EditIcon />}
                      onClick={() => handleEdit(row)}
                    >
                      编辑
                    </Button>
                    <Button
                      theme="primary"
                      variant="text"
                      icon={<EditIcon />}
                      onClick={() => handleEditUserRole(row)}
                    >
                      编辑角色
                    </Button>
                    <Button
                      theme="danger"
                      variant="text"
                      icon={<DeleteIcon />}
                      onClick={() => handleDelete(row)}
                    >
                      删除
                    </Button>
                  </>
                ) : (
                  <Button
                    theme="success"
                    variant="text"
                    icon={<RefreshIcon />}
                    onClick={() => handleRestore(row)}
                  >
                    恢复
                  </Button>
                )}
              </>
            ),
          }
        ]}
      />

      <UserForm
        visible={formVisible}
        onClose={() => setFormVisible(false)}
        onSubmit={handleSubmit}
        initialData={editingUser}
        title={title}
      />
      <UserRoleForm
        visible={formUserRoleVisible}
        onClose={() => setFormUserRoleVisible(false)}
        onSubmit={handleEditUserRoleSubmit}
        initialData={editingUser}
        selectedRoles={selectedRoles || []}
        options={allActiveRoles || []}
      />
    </Card>
  );
}
